#ifndef THREAD_H
#define THREAD_H

#include <pthread.h>
#include <string>
#include <vector>
//#include <tr1/memory>

//#include "bcti_NonCopyable.h"
#include "bcti_Mutex.h"

//using std::tr1::shared_ptr;

enum ThreadStatus{
    Thread_OK = 0,
    Thread_Fail = 1,
    Thread_Pendding,
//    Thread_LoginFail,
//    Thread_InitFail,
    Thread_TimeFail,
    Thread_Interrupted,
//    Thread_BadUrl,
    Thread_BadState,
    Thread_WaitingSelf,
    Thread_TimeOut,
    Thread_Abort,
    Thread_EOF,
    Thread_BadArg,
    Thread_OutOfMemory,
    Thread_NotFound,
};

namespace lzpLib{

class Thread {//: private NonCopyable{
public:
class Runnable{
public:
    virtual void run() = 0;
    virtual ~Runnable(){}
};
    enum State{
        NEW,
        RUNNING,
        TERMINATED,
        JOINED
    };
    Thread(Runnable &target, bool deleteSelf = false, const std::string &name = "unname", int priority = 45, int stackSize = 8192/4);
    ~Thread();

    void start(void);
    const std::string& name(void)       {return name_;}
    int priority(void)                  {return priority_;}
    ThreadStatus setPriority(int priority);
    int stackSize(void)                 {return stackSize_;}
    ThreadStatus wait(int milliseconds);
    int joinThread();

    static ThreadStatus sleep(int milliseconds);
    State state(void)                   {return state_;}
    static ThreadStatus yield();
    static Thread* current(void);


private:
    static void* localstart(void* p);
    void localstart();

    void waitRunning();
    void signalRunning();
    Runnable& target_;
    bool deleteSelf_;
    const std::string name_;
    int priority_;
    int stackSize_;
    volatile State state_;
    pthread_t thread_;
    pthread_mutex_t stateMutex_;
    pthread_cond_t stateCond_;
    pthread_mutex_t stateStartMutex_;
    static std::vector<Thread*> threads_;
    static Mutex threadsMutex_;
};
}
#endif // THREAD_H

